//
//  FitureChildrenContainerView.swift
//  taurus
//
//  Created by dyoung on 2022/1/29.
//  Copyright © 2022 com.fiture. All rights reserved.
//

import UIKit

class FitureCustomPresentNaviAnimation: NSObject {
    var config = FitureCustomPresentConfig()
    init(config: FitureCustomPresentConfig) {
        super.init()
        self.config = config
    }
}

extension FitureCustomPresentNaviAnimation: UIViewControllerAnimatedTransitioning {

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        0.25
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let navi = transitionContext.viewController(forKey: .to) as? UINavigationController,
              let toVC = navi.viewControllers.first,
              let container = toVC.view.subviews.first(where: { $0.isKind(of: FitureChildrenContainerView.self) }) else { return }
        
        let containerView = transitionContext.containerView
        /// 模态的背景遮罩
        let maskview = FitureCustomPresentMaskView()
        maskview.frame = containerView.bounds
        containerView.addSubview(maskview)

        containerView.addSubview(navi.view)
        navi.view.frame = UIScreen.main.bounds
    
        /// animate
        container.snp.makeConstraints { m in
            m.top.equalTo(toVC.view.snp.bottom)
            m.centerX.width.equalTo(toVC.view)
            m.height.equalTo(config.containerViewControllerHeight)
        }
        toVC.view.layoutIfNeeded()
        let topOffset = UIScreen.main.bounds.size.height - config.containerViewControllerHeight
        container.snp.remakeConstraints { m in
            m.top.equalToSuperview().offset(topOffset)
            m.centerX.width.equalToSuperview()
            m.height.equalTo(config.containerViewControllerHeight)
        }
        let duration = transitionDuration(using: transitionContext)
        UIView.animate(withDuration: duration) {
            toVC.view.layoutIfNeeded()
            maskview.alpha = self.config.maskColorAlpha
        } completion: { _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            if transitionContext.transitionWasCancelled {
                maskview.alpha = 0
            }
        }
    }
}



